<!--通行管理-->
<template>
  <div class="log">
    <basic-container>
      <avue-crud
          ref="crud"
          :data="tableData"
          :option="tableOption"
          :page.sync="page"
          :permission="permissionList"
          :table-loading="tableLoading"
          @search-reset="searchReset"
          @on-load="getList"
          @search-change="searchChange"
          @refresh-change="refreshChange"
          @size-change="sizeChange"
          @current-change="currentChange"
          @row-del="handleDel">
        <template slot="menuLeft" slot-scope="scope">
          <el-button
              class="filter-item"
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="handleItem(scope.row)">新增
          </el-button>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
              class="filter-item"
              icon="el-icon-edit"
              size="mini"
              type="primary"
              @click="handleEditItem(scope.row)">编辑
          </el-button>
          <el-button
              class="filter-item"
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="handleDel(scope.row)">删除
          </el-button>
        </template>
        <template slot="state" slot-scope="scope">
          <el-tag v-if="scope.row.state === 1" type="danger">{{ scope.label }}</el-tag>
          <el-tag v-else type="success">{{ scope.label }}</el-tag>
        </template>

      </avue-crud>
      <el-dialog
          :visible.sync="dialogFormVisible"
          title="新增"
          center
          class="dialog-menu" width="60%" @close="dictItemVisible">
        <el-form v-model="addform">
          <el-form-item label="填写方案名">
            <el-input v-model="addform.schemeName" placeholder="请输入方案名" style="width: 20%"></el-input>
          </el-form-item>
          <el-form-item label="指定起止时间">
            <el-col :span="5">
              <avue-date v-model="addform.validTimeStart" format="yyyy年MM月dd日" placeholder="请选择开始日期"
                         value-format="yyyy-MM-dd"></avue-date>
            </el-col>
            <el-col :span="5">
              <avue-date v-model="addform.validTimeEnd" format="yyyy年MM月dd日" placeholder="请选择结束日期"
                         value-format="yyyy-MM-dd"></avue-date>
            </el-col>
          </el-form-item>
        </el-form>
        <avue-crud
            ref="crudItem"
            :data="tableDictItemData"
            :option="tableDictItemOption"
            :page.sync="itemPage"
            :permission="permissionList"
            @size-change="itemSizeChange"
            @current-change="itemCurrentChange"
            @selection-change="selectionChange">
          <template slot="inTimeBuild" slot-scope="scope">
            <span v-if="scope.row.inTime !== null">{{ scope.row.inTime }}</span>
            <span v-else>{{ scope.row.timeInBuild }}</span>
          </template>
          <template slot="outTimeBuild" slot-scope="scope">
            <span v-if="scope.row.outTime !== null">{{ scope.row.outTime }}</span>
            <span v-else>{{ scope.row.timeOutBuild }}</span>
          </template>
        </avue-crud>
        <div slot="footer">
          <el-button
              class="filter-item"
              size="small"
              @click="dictItemVisible">取消
          </el-button>
          <el-button
              class="filter-item"
              size="small"
              type="primary"
              @click="handleItemSave">确定
          </el-button>
        </div>
      </el-dialog>

      <el-dialog
          :visible.sync="dialogEditVisible"
          title="编辑"
          center
          class="dialog-menu" width="60%" @close="dictItemVisible">
        <el-form v-model="editform">
          <el-form-item label="填写方案名">
            <el-input v-model="editform.schemeName" placeholder="请输入方案名" style="width: 20%"></el-input>
          </el-form-item>
          <el-form-item label="指定起止时间">
            <el-col :span="5">
              <avue-date v-model="editform.validTimeStart" format="yyyy年MM月dd日" placeholder="请选择开始日期"
                         value-format="yyyy-MM-dd"></avue-date>
            </el-col>
            <el-col :span="5">
              <avue-date v-model="editform.validTimeEnd" format="yyyy年MM月dd日" placeholder="请选择结束日期"
                         value-format="yyyy-MM-dd"></avue-date>
            </el-col>
          </el-form-item>
        </el-form>
        <avue-crud
            ref="crudItem"
            :data="tableEditItemData"
            :option="tableEditItemOption"
            :page.sync="editPage"
            :permission="permissionList"
            @size-change="itemEditSizeChange"
            @current-change="itemEditCurrentChange"
            @selection-change="selectionEditChange">
          <template slot="inTimeBuild" slot-scope="scope">
            <span v-if="scope.row.inTime !== null">{{ scope.row.inTime }}</span>
            <span v-else>{{ scope.row.timeInBuild }}</span>
          </template>
          <template slot="outTimeBuild" slot-scope="scope">
            <span v-if="scope.row.outTime !== null">{{ scope.row.outTime }}</span>
            <span v-else>{{ scope.row.timeOutBuild }}</span>
          </template>
        </avue-crud>
        <div slot="footer">
          <el-button
              class="filter-item"
              size="small"
              @click="dictItemVisible">取消
          </el-button>
          <el-button
              class="filter-item"
              size="small"
              type="primary"
              @click="handleEditSave">确定
          </el-button>
        </div>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {addPassObj, beforeEditObj, delPassObj, editPassObj, passIndexObj} from '@/api/pass/pass'
import {tableDictItemOption, tableEditItemOption, tableOption} from '@/const/crud/pass/pass'
import {mapGetters} from 'vuex'
import {timeSlotObj} from "@/api/pass/time-slot";

export default {
  name: 'index',
  data() {
    return {
      addOrUpdateVisible: false,
      dialogFormVisible: false,      //新增弹窗
      dialogEditVisible: false,       //编辑弹窗
      tableData: [],
      tableDictItemData: [],
      tableEditItemData: [],
      searchForm: {},
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      itemPage: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 5, // 每页显示多少条
        pageSizes: [5, 10, 20, 30, 40]
      },
      editPage: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: this.total, // 每页显示多少条
        pageSizes: [100]
      },
      tableLoading: false,
      tableOption: tableOption,
      tableDictItemOption: tableDictItemOption,
      tableEditItemOption: tableEditItemOption,
      timeSectionIds: [],
      bindingTimeSectionId: [],        //编辑弹窗中有编辑操作的已绑定时间段
      // unbindTimeSection: [],           //编辑弹窗中有编辑操作的未绑定时间段
      list: [],
      bindlist: [],
      unbindlist: [],
      addform: {
        schemeName: '',
        validTimeStart: '',
        validTimeEnd: ''
      },
      editform: {
        schemeName: '',
        validTimeStart: '',
        validTimeEnd: ''
      },
      // flag: true,//单位切换开关
      // btnText: '选择',
      chooseList: [],
      selectedList: [],
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList() {
      return {
        delBtn: this.vaildData(this.permissions.sys_time_del, true),
      }
    }
  },
  methods: {
    // 列表展示相关
    getList(page, params) {
      this.tableLoading = true
      passIndexObj(Object.assign({
        descs: 'create_time',  //是否倒序
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      })
    },
    handleDel: function (row) {
      this.$confirm('是否确认删除"' + row.schemeName + '"的时间方案?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delPassObj(row.id)
      }).then(() => {
        this.getList(this.page)
        this.$message.success('删除成功')
      })
    },
    searchChange(form, done) {
      this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    currentChange(current) {
      this.page.currentPage = current
    },
    refreshChange() {
      this.getList(this.page)
    },
    //新增弹窗相关
    handleItem: function (row) {
      this.getDictItemList()
    },
    dictItemVisible(val) {
      this.dialogFormVisible = false
      this.dialogEditVisible = false
      this.itemPage.currentPage = 1
      this.addform = {}
      this.$refs.crudItem.toggleSelection(val);
    },
    itemCurrentChange(current) {
      this.itemPage.currentPage = current
      this.getDictItemList()
    },
    itemSizeChange(pageSize) {
      this.itemPage.pageSize = pageSize
      this.getDictItemList()
    },
    //新增弹窗的展示列表
    getDictItemList(params) {
      this.dialogFormVisible = true
      timeSlotObj(Object.assign({
        descs: 'create_time',  //是否倒序
        current: this.itemPage.currentPage,
        size: this.itemPage.pageSize
      }, params)).then(response => {
        this.tableDictItemData = response.data.data.records
        this.itemPage.total = response.data.data.total
      })
    },
    // 表格的多选方法
    selectionChange(list) {
      // this.$message.success('选中的数据'+ JSON.stringify(list));
      this.chooseList = list
    },
    // 编辑表格的多选方法
    selectionEditChange(list) {
      // this.$message.success('选中的数据'+ JSON.stringify(list));
      this.selectedList = list
    },
    //新增保存
    handleItemSave: function (row, val) {
      if (this.addform.schemeName === ''){
        this.$message.error('添加失败，请输入方案名')
        return
      }
      if (this.addform.validTimeStart === ''){
        this.$message.error('添加失败，请选择开始日期')
        return
      }
      if (this.addform.validTimeEnd === ''){
        this.$message.error('添加失败，请选择结束日期')
        return
      }
      let ids = this.chooseList.map(x => {
        return x.id
      })
      console.log(ids)
      this.timeSectionIds = ids
      let param = {
        "schemeName": this.addform.schemeName,
        "groupNum": 2,
        "timeSectionIds": this.timeSectionIds,
        "validTimeStart": this.addform.validTimeStart,
        "validTimeEnd": this.addform.validTimeEnd,
      }
      addPassObj(param).then(res => {
        if (res.data.code === 0) {
          this.$message.success('添加成功')
        } else {
          this.$message.error('添加失败')
        }
        // done()
        this.getList(this.page)
        this.dialogFormVisible = false
        this.$refs.crudItem.toggleSelection(val);
      })
    },
    //编辑弹窗相关
    handleEditItem: function (row) {
      this.schemeId = row.id
      this.getEditItemList()
    },
    itemEditCurrentChange(current) {
      this.editPage.currentPage = current
      this.getEditItemList()
    },
    itemEditSizeChange(pageSize) {
      this.editPage.pageSize = pageSize
      this.getEditItemList()
    },
    //获取编辑的方案的内容 以及已绑定和未绑定的时间段
    getEditItemList() {
      this.dialogEditVisible = true
      let param = {
        schemeId: this.schemeId,
        size: 999,
        descs: 'create_time',  //是否倒序
      }
      beforeEditObj(param).then(res => {
        if (res.data.code === 0) {
          //反参的data内包含两个对象，第一个[0]是方案的内容  第二个[1]里面才是records数组
          this.tableEditItemData = res.data.data[1].records
          this.timeSectionIds = res.data.data[0].timeSectionIds
          this.editform = res.data.data[0]
          this.editPage.total = res.data.data[1].total
          this.tableEditItemData.map(i => {
            this.timeSectionIds.map(j => {
              if (i.id === j) {
                this.$nextTick(() => {
                  this.$refs.crudItem.toggleRowSelection(i);
                })
              }
            })
          })
        }
      })

    },
    //保存修改信息
    handleEditSave: function (row, done) {
      // debugger
      console.log(this.selectedList)
      this.bindingTimeSectionId = this.selectedList.map(x => {
        return x.id
      })
      let param = {
        "id": this.editform.id,
        "schemeName": this.editform.schemeName,
        "groupNum": 2,
        "bindingTimeSectionId": this.bindingTimeSectionId,
        "validTimeStart": this.editform.validTimeStart,
        "validTimeEnd": this.editform.validTimeEnd,
      }
      console.log(param)
      // debugger
      editPassObj(param).then(res => {
        if (res.data.code === 0) {
          this.$message.success('修改成功')
        } else {
          this.$message.error('修改失败')
        }
        // done()
        this.getList(this.page)
        this.dialogEditVisible = false
      })
    },
    searchReset() {
      this.page = {};
      this.searchForm = 0;
      this.getList(this.page)
    }
  }
}
</script>
<style>
.dialog-menu .avue-crud__menu {
  display: none;
}
</style>
<style scoped>
/deep/.el-form-item__label{
  text-align: left;
}
/deep/.avue-form__row {
  padding-left: 0 !important;
  margin-right: 36px;
}
</style>